package org.garbagecan.xstreamstudy.userconf;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class ViewPreferenceConverter implements Converter {
	public boolean canConvert(Class clazz) {
		return clazz.equals(ViewPreference.class);
	}

	public void marshal(Object value, HierarchicalStreamWriter writer,
			MarshallingContext context) {
		ViewPreference viewPreference = (ViewPreference) value;
		writer.startNode("ViewPreference");
		writer.addAttribute("Type", viewPreference.getType());
		boolean enableAutoRefresh = viewPreference.isEnableAutoRefresh();
		writer.addAttribute("EnableAutoRefresh", (enableAutoRefresh) ? "Y" : "N");
		writer.addAttribute("MaxPageSize", "" + viewPreference.getMaxPageSize());
		writer.addAttribute("RefreshTime", "" + viewPreference.getRefreshTime());
		writer.addAttribute("SelectedColumns", viewPreference.getSelectedColumns());
		writer.addAttribute("UnselectedColumns", viewPreference.getUnselectedColumns());
		writer.addAttribute("SortBy", viewPreference.getSortBy());
		writer.addAttribute("SortDir", viewPreference.getSortDir());
		writer.addAttribute("TitleName", viewPreference.getTitleName());
		writer.endNode();
	}

	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {
		ViewPreference viewPreference = new ViewPreference();
		reader.moveDown();
		viewPreference.setType(reader.getAttribute("Type"));
		String enableAutoRefresh = reader.getAttribute("EnableAutoRefresh");
		viewPreference.setEnableAutoRefresh((enableAutoRefresh.equals("Y") ? true : false));
		viewPreference.setMaxPageSize(Integer.parseInt(reader.getAttribute("MaxPageSize")));
		viewPreference.setRefreshTime(Integer.parseInt(reader.getAttribute("RefreshTime")));
		viewPreference.setSelectedColumns(reader.getAttribute("SelectedColumns"));
		viewPreference.setUnselectedColumns(reader.getAttribute("UnselectedColumns"));
		viewPreference.setSortBy(reader.getAttribute("SortBy"));
		viewPreference.setSortDir(reader.getAttribute("SortDir"));
		viewPreference.setTitleName(reader.getAttribute("TitleName"));
		reader.moveUp();
		return viewPreference;
	}
}
